#! /usr/bin/perl
#
# packlister.pl prints out the given version number and a list of
# packages found in the corresponding catalyst package cache and
# grp cache.
#
# Usage: packlister.pl <version>
#        packlister.pl <version> | reducedsnapshot.pl
#        packlister.pl <version> > packlisterfile

sub find_and_dump
{
	if (scalar @_ == 0)
	{
		return;
	}
	
	open (FIND, "find $_ -name '*.tbz2' -exec ls -Ls {} \\; | "
		. "grep -v '/All/' |");
	
	while (<FIND>)
	{
		if (/^(\d+)\s+(.+)\/([A-Za-z0-9+_]+[A-Za-z0-9+_.-]*)\/(.+)$/)
		{
			$size = $1;
			$cstage = $2;
			$cat = $3;
			$name = $4;
			
			# There might be more than x86 supported in future versions.
			if ($cstage =~ /.*\/(.+)-x86-.+/)
			{
				$stage=$1;
			}
			else
			{
				print STDERR "ERROR ($cstage)\n";
			}
			
			# FIXME: The second regex (elsif) seems to match the stuff
			# the first one also matches. Is this needed?
			if ($name =~ /^(.+)-(.+-r\d+)\.tbz2/)
			{
				$packages{"$cat/$1"} = "$2 - $size Kb - $stage";
			} 
			elsif ($name =~ /^(.+)-(.+)\.tbz2/)
			{
				$packages{"$cat/$1"} = "$2 - $size Kb - $stage";
			} 
			else
			{
				print STDERR "ERROR ($name)\n"
			}	
		}
		else
		{
			print STDERR "ERROR : $_";
		}
	}
	
	close (FIND);
}

# Check script parameters
if (scalar @ARGV == 0)
{
	die "Usage: $ENV{_} <version>\n";
}

# Print version and file list based on catalyst
print "$ARGV[0]\n";
&find_and_dump("/var/tmp/catalyst/packages/gnap/*$ARGV[0]");
&find_and_dump("/var/tmp/catalyst/packages/gnap/grp*$ARGV[0]/*");

#No need to grab for kernel sources as they are found in the /ALL/ directory
#$kernel=`grep sys-kernel gnap_make-$ARGV[0].out | grep merged | grep sources`;
#if ($kernel =~ /(sys-kernel\/.*-sources)-(.*) merged/)
#{
#  $packages{$1} = "$2 - n/a - livecd-stage2";
#}
#else
#{
#  print STDERR "Kernel not found: $kernel\n";
#}

foreach $key (sort(keys(%packages)))
{
	print STDOUT "$key $packages{$key}\n";
}

#Groff is part of the stage3 tarball but not remerged so we have to add it manually
print STDOUT "sys-apps/groff 1.19.2-r1 - 116 Kb - stage3\n";
#htbinit is merged with kernel sources and somehow missed by the script
print STDOUT "net-misc/htbinit 0.8.5-r1 - 116 Kb - livecd-stage2\n";
